//
//  SetPayPasswordViewController.m
//  HuaMuJinRong
//
//  Created by 吴建东 on 16/4/18.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "SetPayPasswordViewController.h"
#import "VerifyMobileViewController.h"

@interface SetPayPasswordViewController ()<HTTPClientDelegate,UIAlertViewDelegate>
{
    NSString *_oldPasswordStr;
    NSString *_newPasswordStr;
    NSString *_surePasswordStr;
    
    UIView  *_verifyPwdSuccessView;
    UIView  *_inputErrorView;
    UILabel *_errorNumLabel;
    NSInteger _errorNum;
    
    BOOL _isShowSetView;
}
@property (nonatomic, assign) NSInteger      operationStaus;  //1输入旧密码 2输入新密码 3确认新密码
@property (nonatomic, assign) BOOL           isSecurity;
@property (nonatomic, strong) NSArray        *titleArray;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, copy  ) NSString       *pwdStr;
@property (nonatomic, strong) UIView         *setView;
@property (nonatomic, strong) UIView         *backView;
@property (nonatomic, strong) UIView         *keyBoardView;
@property (nonatomic, strong) UIView         *enterView;
@property (nonatomic, strong) UIButton       *cancelButton;
@property (nonatomic, strong) UILabel        *operationNameLabel;
@property (nonatomic, strong) UITextField    *passwordTextField;
@property (weak, nonatomic) IBOutlet UIButton *findPwdButton;

@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) NSInteger     requestType;
@property (nonatomic, assign) BOOL          isLoading;

@end

@implementation SetPayPasswordViewController
#pragma mark - Life Cycle
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_isShowSetView) {
        _isShowSetView = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (iOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    if (self.editType == 1) {
        [self initNavBarTitle:@"设置交易密码" andLeftItemName:@"返回" andRightItemName:@""];
        _operationStaus = 2;
        _findPwdButton.hidden = YES;
    }else {
        [self initNavBarTitle:@"修改交易密码" andLeftItemName:@"返回" andRightItemName:@""];
        _operationStaus = 1;
        _findPwdButton.hidden = NO;
    }
    
    [self initData];
    [self initView];
}


#pragma mark - Action
- (void)dealSetCancelViewTap {
    [_setView removeFromSuperview];
}

- (void)cancelButtonClick {
    [_setView removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)findPwdButtonClick:(id)sender {
    //先验证手机号码
    VerifyMobileViewController *verifyMobile = [[VerifyMobileViewController alloc] init];
    verifyMobile.viewType = ResetDealPassword;
    verifyMobile.naviTitle = @"验证手机号";
    verifyMobile.mobileStr = AppDelegateInstance.userInfo.mobile;
    [self.navigationController pushViewController:verifyMobile animated:YES];
}

- (void)numButtomClick:(UIButton *)button {
    NSInteger index = button.tag - 100;
    if (index == 11) {
        if (_dataArr.count > 0) {
            [_dataArr removeLastObject];
        }
    }else if (index == 9) {
        
    }else {
        if (_dataArr.count < 6) {
            [_dataArr addObject:_titleArray[index]];
        }
        if (_dataArr.count >= 6) {
            [self inputSuccess];
        }
    }
    [self reloadEnterView];
}

- (void)inputSuccess {
    if (_operationStaus == 1) {
        _oldPasswordStr = [_dataArr componentsJoinedByString:@""];
        [self verifyOldPasswordRequest];
        return;
    }else if (_operationStaus == 2) {
        _newPasswordStr = [_dataArr componentsJoinedByString:@""];
    }else if (_operationStaus == 3) {
        _surePasswordStr = [_dataArr componentsJoinedByString:@""];
        if (![_newPasswordStr isEqualToString:_surePasswordStr]) {
            [SVProgressHUD showErrorWithStatus:@"两次输入的密码不一致，请重新输入！"];
            _surePasswordStr = @"";
            
            _operationStaus = 2;
            [self reloadOperationStaus];
            return;
        }
    }
    _operationStaus ++;
    if (_operationStaus > 3) {
        [self setDealPasswordRequest];
    }else {
        [self reloadOperationStaus];
    }
}

- (void)reloadOperationStaus {
    if (_operationStaus == 1) {
        _operationNameLabel.text = @"输入旧交易密码";
    }else if (_operationStaus == 2) {
        _operationNameLabel.text = @"输入新交易密码";
    }else {
        _operationNameLabel.text = @"确认新交易密码";
    }
    [_dataArr removeAllObjects];
    [self reloadEnterView];
}

- (void)reloadEnterView {
    for (UIView *subView in _enterView.subviews) {
        if ([subView isKindOfClass:[UITextField class]]) {
            UITextField *textField = (UITextField *)subView;
            textField.text = @"";
        }
    }
    if (_dataArr.count > 0) {
        for (NSInteger i=0; i < _dataArr.count; i++) {
            UITextField *textField = [_enterView viewWithTag:200 + i];
            if (_isSecurity) {
                textField.text = @"●";
            }else {
                textField.text = _dataArr[i];
            }
        }
    }
}

- (void)reloadErrorNum:(NSInteger)errorNum {
//    _errorNumLabel.text = [NSString stringWithFormat:@"交易密码不正确，您还可以输入%ld次",3-errorNum];
    _errorNumLabel.text = [NSString stringWithFormat:@"原交易密码不正确"];
    [self inputErrorViewShow];
}

- (void)inputButtonClick {
    
    [self inputErrorViewHidden];
}

- (void)forgetPwdButtonClick {
    
    _setView.hidden = YES;
    _inputErrorView.hidden = YES;
    _keyBoardView.hidden = NO;
    
    [_dataArr removeAllObjects];
    [self reloadEnterView];
    
    //先验证手机号码
    VerifyMobileViewController *verifyMobile = [[VerifyMobileViewController alloc] init];
    verifyMobile.viewType = ResetDealPassword;
    verifyMobile.naviTitle = @"验证手机号";
    verifyMobile.mobileStr = AppDelegateInstance.userInfo.mobile;
    [self.navigationController pushViewController:verifyMobile animated:YES];
    
}

- (void)inputErrorViewShow {
    _keyBoardView.hidden = YES;
    _inputErrorView.hidden = NO;
    [AppDelegateInstance.window bringSubviewToFront:_inputErrorView];
}

- (void)inputErrorViewHidden {
    _keyBoardView.hidden = NO;
    _inputErrorView.hidden = YES;
    [self reloadOperationStaus];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 11) {
        if (buttonIndex == 0) {
            [self cancelButtonClick];
        }
    }
}

#pragma mark - 请求数据
- (void)initData {
    _isSecurity = YES;
    _dataArr = [NSMutableArray array];
    _pwdStr = @"";
    _titleArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"L",@"0",@"X"];
    
}


- (void)setDealPasswordRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求，请稍候再试..."];
        return;
    }
    
    _requestType = 2;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if (self.editType == 1) {
        [parameters setObject:@"103" forKey:@"OPT"];
    }else {
        [parameters setObject:@"104" forKey:@"OPT"];
    }
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    [parameters setObject:[NSString encrypt3DES:_newPasswordStr key:DESkey] forKey:@"newdealpwd"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

- (void)verifyOldPasswordRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求，请稍候再试..."];
        return;
    }
    
    _requestType = 1;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"510" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    [parameters setObject:[NSString encrypt3DES:_oldPasswordStr key:DESkey] forKey:@"currentdealpwd"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma - 网络数据回调代理
- (void)startRequest {
    _isLoading = YES;
    
    _setView.userInteractionEnabled = NO;
}

// 返回成功
- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    _setView.userInteractionEnabled = YES;
    NSDictionary *dics = obj;
    DLOG(@"dic=%@",dics);
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        if (_requestType == 1) {
            [self verifyPasswordSuccessView];
            
        }else if (_requestType == 2) {
            if (self.editType == 1) {
                AppDelegateInstance.userInfo.isPayPasswordStatus = YES;
                //AppDelegateInstance.isUpdateAccount = YES;
                if (self.delegate && [self.delegate respondsToSelector:@selector(setPayPasswordSuccess)]) {
                    [self.delegate setPayPasswordSuccess];
                }
            }
            [SVProgressHUD showImage:nil status:dics[@"msg"]];
            [self cancelButtonClick];
        }
        
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        [self reloadOperationStaus];
        
        [ReLogin outTheTimeRelogin:self];
    }else {
        if (_requestType == 1) {
            /*
            _errorNum ++;
            if (_errorNum < 3) {
                if (_inputErrorView == nil) {
                    [self initInputErrorView];
                }else {
                    [self reloadErrorNum:_errorNum];
                }
                [self reloadOperationStaus];
            }else {
                UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"密码错误次数过多" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alertview.tag = 11;
                [alertview show];
            }*/
            if (_inputErrorView == nil) {
                [self initInputErrorView];
            }else {
                [self reloadErrorNum:_errorNum];
            }
            [self reloadOperationStaus];
            
        }else if (_requestType == 2) {
            _operationStaus = 2;
            _newPasswordStr = @"";
            [self reloadOperationStaus];
        }
        [SVProgressHUD showImage:nil status:[dics objectForKey:@"msg"]];
    }
    
}

// 返回失败
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    _setView.userInteractionEnabled = YES;
}

// 无可用的网络
- (void)networkError {
    //  [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
    _isLoading = NO;
    _setView.userInteractionEnabled = YES;
}



#pragma mark - View
- (void)verifyPasswordSuccessView {
    _verifyPwdSuccessView = [UIView viewWithFrame:RECTMAKE(0, KAdaptNum(40), MSWIDTH, GetHeight(_backView)-KAdaptNum(40)) backgroundColor:[UIColor whiteColor] superview:_backView];
    
    UIImageView *successImageView = [UIImageView imageViewWithFrame:RECTMAKE((MSWIDTH - 50)/2, 60, 50, 50) imageFile:@"VerifyPwdSuccess" superview:_verifyPwdSuccessView];
    
   UILabel *label = [UILabel labelWithFrame:RECTMAKE(10, GetMaxY(successImageView) + 10, MSWIDTH - 20, KAdaptNum(20)) text:@"验证成功" textColor:GreenColor textFont:14 fitWidth:YES superview:_verifyPwdSuccessView];
    label.textAlignment = NSTextAlignmentCenter;
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [_verifyPwdSuccessView removeFromSuperview];
        _operationStaus++;
        [self reloadOperationStaus];
    });
    
}

- (void)initView {
    _findPwdButton.titleLabel.font = KFontSize(14);
    
    _setView = [UIView viewWithFrame:RECTMAKE(0, 0, MSWIDTH, MSHIGHT) backgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.3] superview:AppDelegateInstance.window];
    
    UIView *cancelView = [UIView viewWithFrame:RECTMAKE(0, 0, MSWIDTH, GetHeight(_setView) - KAdaptNum(320)) backgroundColor:nil superview:_setView];
    [cancelView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dealSetCancelViewTap)]];
    
    _backView = [UIView viewWithFrame:RECTMAKE(0, GetHeight(_setView) - KAdaptNum(320), MSWIDTH, KAdaptNum(320)) backgroundColor:[UIColor whiteColor] superview:_setView];
    
    _cancelButton = [UIButton buttonWithFrame:RECTMAKE(0, 0, KAdaptNum(40), KAdaptNum(40)) backgroundColor:nil title:@"" titleColor:nil titleFont:0 target:self action:@selector(cancelButtonClick) superview:_backView];
    [_cancelButton setImage:[UIImage imageNamed:@"SetPayPwd_Cancel"] forState:UIControlStateNormal];
    
    _operationNameLabel = [UILabel labelWithFrame:RECTMAKE(10, 0, MSWIDTH - 20, KAdaptNum(40)) text:@"" textColor:KBlackColor textFont:16 fitWidth:NO superview:_backView];
    _operationNameLabel.textAlignment = NSTextAlignmentCenter;
    [self reloadOperationStaus];
    
    [UIView viewWithFrame:RECTMAKE(0, KAdaptNum(40)-1, MSWIDTH, 1) backgroundColor:KlayerBorder superview:_backView];
    
    _keyBoardView = [UIView viewWithFrame:RECTMAKE(0, KAdaptNum(40), MSWIDTH, GetHeight(_backView) - KAdaptNum(40)) backgroundColor:[UIColor whiteColor] superview:_backView];
    
    
    _enterView = [UIView viewWithFrame:RECTMAKE(10, KAdaptNum(20), MSWIDTH - 20, KAdaptNum(40)) backgroundColor:[UIColor whiteColor] superview:_keyBoardView];
    _enterView.layer.cornerRadius = 3.0f;
    _enterView.layer.borderColor = KlayerBorder.CGColor;
    _enterView.layer.borderWidth = 1.0f;
    
    for (NSInteger i=0; i < 6; i++) {
        UITextField *textField = [UITextField textFieldWithFrame:RECTMAKE((GetWidth(_enterView)/6)*i, 0, GetWidth(_enterView)/6, GetHeight(_enterView)) delegate:self text:@"" textColor:KBlackColor textFont:16 placeholder:@"" superview:_enterView];
        textField.userInteractionEnabled = NO;
        textField.tag = 200 + i;
        textField.textAlignment = NSTextAlignmentCenter;
        
        if (i < 5) {
            [UIView viewWithFrame:RECTMAKE(((GetWidth(_enterView))/6)*(i+1), 0, 1, GetHeight(_enterView)) backgroundColor:KlayerBorder superview:_enterView];
        }
    }
    
    for (NSInteger i=0; i < _titleArray.count; i++) {
        double w = MSWIDTH/3;
        double h = KAdaptNum(50);
        double x = w * (i%3);
        double y = GetMaxY(_enterView) + KAdaptNum(20) + h * (i/3);
        
        UIButton *button = [UIButton buttonWithFrame:RECTMAKE(x, y, w, h) backgroundColor:nil title:_titleArray[i] titleColor:KBlackColor titleFont:16 target:self action:@selector(numButtomClick:) superview:_keyBoardView];
        button.titleLabel.font = KFontBoldSize(16);
        button.tag = 100 + i;
        if (i == 9) {
            [button setTitle:@"" forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"ModifyDealPwd_Logo"] forState:UIControlStateNormal];
        }else if (i == 11) {
            [button setTitle:@"" forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"ModifyDealPwd_Delete"] forState:UIControlStateNormal];
        }
    }
    
    for (NSInteger i=0; i < 5; i++) {
        [UIView viewWithFrame:RECTMAKE(0, GetMaxY(_enterView) + KAdaptNum(20) + KAdaptNum(50) * i, MSWIDTH, 1) backgroundColor:KlayerBorder superview:_keyBoardView];
    }
    for (NSInteger i=0; i < 4; i++) {
        [UIView viewWithFrame:RECTMAKE(MSWIDTH/3*(i+1), GetMaxY(_enterView) + KAdaptNum(20), 1, KAdaptNum(50)*4) backgroundColor:KlayerBorder superview:_keyBoardView];
    }
}

- (void)initInputErrorView {
    _keyBoardView.hidden = YES;
    
    _inputErrorView = [UIView viewWithFrame:RECTMAKE(0, 0, MSWIDTH, MSHIGHT) backgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.3] superview:AppDelegateInstance.window];
    
    UIView *errorBackView = [UIView viewWithFrame:RECTMAKE(30, (MSHIGHT - KAdaptNum(320)) + (KAdaptNum(320) - KAdaptNum(120))/2, MSWIDTH - 60, KAdaptNum(120)) backgroundColor:[UIColor whiteColor] superview:_inputErrorView];
    errorBackView.layer.cornerRadius = KAdaptNum(5.0);
    
    _errorNumLabel = [UILabel labelWithFrame:RECTMAKE(20, 0, GetWidth(errorBackView) - 40, KAdaptNum(120) - KAdaptNum(36) - 20) text:[NSString stringWithFormat:@"原交易密码不正确"] textColor:KBlackColor textFont:14 fitWidth:NO superview:errorBackView];
    _errorNumLabel.textAlignment = NSTextAlignmentCenter;
    _errorNumLabel.numberOfLines = 0;
    
    ClickButton *inputButton = [[ClickButton alloc] initWithFrame:RECTMAKE(20, GetHeight(errorBackView) - 10 - KAdaptNum(36), (GetWidth(errorBackView)-60)/2, KAdaptNum(36))];
    [inputButton setTitle:@"重新输入" forState:UIControlStateNormal];
    [inputButton addTarget:self action:@selector(inputButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [errorBackView addSubview:inputButton];
    inputButton.titleLabel.font = KFontSize(14.0);
    inputButton.alpha = 0.6;
    
    ClickButton *forgetButton = [[ClickButton alloc] initWithFrame:RECTMAKE(GetMaxX(inputButton) + 20, GetMinY(inputButton), (GetWidth(errorBackView)-60)/2, KAdaptNum(36))];
    [forgetButton setTitle:@"忘记密码" forState:UIControlStateNormal];
    [forgetButton addTarget:self action:@selector(forgetPwdButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [errorBackView addSubview:forgetButton];
    forgetButton.titleLabel.font = KFontSize(14.0);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
